#!/usr/bin/env python

import os,json,shutil,string,time,urllib2

#the path of photos is saved in info.txt

def log(type,tag,txt) :

    print(type + ": " + tag + " " + txt)

def getInfo() :
    #read connected devices
    res = os.popen("gphoto2 --auto-detect").read()
    #count devices
    n = res.count('\n')
    if n == 2:
        return 100
        #there are no devices

    collection = res.split('\n')

    res = []

    for item in collection:
        index = item.find('usb')
        if index != -1:
            res.append(item[index:index + 11])

    return res

def getSerial(port) :
    #read data form a port
    res = os.popen("gphoto2 --summary --port " + port).read()
    #select serial
    pos = res.rfind("Serial Number")
    if pos == -1 :
        return 200
    else :
        res = res[pos + 15:]
        res = res.split('\n')
        return res[0]

def movePhotos(sPath,tPath,DeviceId) :
    if not os.path.isdir(sPath) or not os.path.isdir(tPath) :
        log("error","movePhotos",tPath)
        return False

    for x in os.listdir(sPath) :
	#add extra path to the filename
        if x.rfind('.') != -1:
            filename = DeviceId + '_' + x[0:x.rfind('.')]
            ext = x[x.rfind('.'):]
            n = filename + ext
        else:
            n = DeviceId + "_" + x

        shutil.copyfile(sPath+"/"+x,tPath+"/"+n)
        os.remove(sPath+"/"+x)

    return True

def mount() :

    global mountPath, password, ip, url, user

    try:
        path = urllib2.urlopen(url + "?act=get_path", data=None, timeout=TIME_OUT).read()
        res = os.popen("mount -l | grep " + ip).read()

        if len(res) == 0 :
            os.popen("sudo ./mount.exp "\
                    + user + "@" + ip + ":" + path + " "\
                    + mountPath + " " + password)

            res = os.popen("mount -l | grep " + ip).read()

            if len(res) == 0 :
                return False
            else:
                return True
        else:
            return True

    except Exception,e:
        print(str(e))
        return False

def umount() :

    global mountPath, ip

    os.popen("sudo umount " + mountPath)

    res = os.popen("mount -l | grep " + ip).read()
    if len(res) == 0 :
        return True
    else :
        return False

def carryer(port,url,cache,tPath) :

    DeviceSerial = getSerial(port);
    TAG = "carryer"

    try :
        data = urllib2.urlopen(url + "?act=query_state&serial=" + DeviceSerial, data=None, timeout=TIME_OUT).read()
        if data == '0':
            return False
    except Exception,e:
        log(TYPE_ERROR,TAG,str(e))
        return False



    try :
        data = urllib2.urlopen(url + "?act=register&serial=" + DeviceSerial + "&dir="+tPath[tPath.rfind('/'):], data=None, timeout=TIME_OUT).read()
        if data == '0':
            return False

    except Exception,e:
        log(TYPE_ERROR,TAG,str(e))
        return False


    try :
        data = urllib2.urlopen(url + '/?act=login&serial=' + DeviceSerial, data=None, timeout=TIME_OUT).read()
        log(TYPE_INFO,TAG,DeviceSerial + ' start moving the photos.')

        #send photos to cache
        log(TYPE_INFO,TAG,DeviceSerial + ' start moving the photos to the cache.')
        os.chdir(cache)
        os.popen('gphoto2 -P --skip-existing --port ' + port)
        log(TYPE_INFO,TAG,DeviceSerial + ' finish moving the photos to the cache.')

        log(TYPE_INFO,TAG,DeviceSerial + ' start cleaning camera.')
        os.popen('gphoto2 -R -D --port ' + port)
        log(TYPE_INFO,TAG,DeviceSerial + ' finish cleaning camera.')
        os.chdir('..')
        log(TYPE_INFO,TAG,DeviceSerial + ' start moving the photos to the server.')
        movePhotos(cache,tPath,DeviceSerial)
        log(TYPE_INFO,TAG,DeviceSerial + ' finish moving the photos to the server.')

        log(TYPE_INFO,TAG,DeviceSerial + ' finish moving the photos.')
        data = urllib2.urlopen(url + '/?act=logout&serial=' + DeviceSerial, data=None, timeout=TIME_OUT).read()

        return True
    except Exception,e :
        log(TYPE_ERROR,TAG,str(e))
        return False

def fileManager() :

    TAG = "fileManager"

    f1 = True

    while f1 :
        global url, cache, mountPath

        try :
            path = urllib2.urlopen(url + "?act=get_dir", data=None, timeout=TIME_OUT).read()
            newPath = mountPath + path
        except Exception,e :
            log(TYPE_ERROR,TAG,str(e))
            continue

        resList = getInfo()

        if type(resList) == int :
            if resList == 100 :
                log(TYPE_INFO,TAG,str(resList) + ' no device was found.')
            continue

        print("=================")
        print("Start sending ...")

        for port in resList :

            carryer(port,url,cache,newPath)

        print("Sending end ...")
        print("=================")

        time.sleep(2)

if __name__ == '__main__':

    global setFile, url, cache, mountPath, password, ip, user, setFile, TYPE_INFO, TYPE_ERROR, TIME_OUT
    setFile = "setting.json"
    TYPE_INFO = "info"
    TYPE_ERROR = "error"
    TIME_OUT = 5

    print("System start.")

    if not os.path.isfile(setFile) :
        log(TYPE_ERROR,TAG,"setting.json didn't exist.\nPlease check.")
        exit()

    fp = open(setFile,'r')
    info = json.loads(fp.read())
    fp.close()

    url = info['url']
    cache = info['cache']
    user = info['user']
    mountPath = info['mountPath']
    password = info['password']
    ip = info['ip']

    f1 = True
    while f1 :
        if mount() :
            print("mount success!")
            f1 = False
        else :
            print("there are errors in mount. Will retry in 2 sec.")
            time.sleep(2)

    try :
        fileManager()

    except KeyboardInterrupt :
        if umount() :
            print("umount success!")
        else :
            print("there are errors in umount")

    print("System down.")
